﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using VAdvantage.Utility;
using VAdvantage.Panels;
using VAdvantage.DataService;
using SilverlightDesktop.Controls;
using VAdvantage.Process;
using System.Threading;
using VAdvantage.Classes;
using VAdvantage.Framework;
using VAdvantage.Search;
using VAdvantage.Apps;
//using SlEmail;
using VAdvantage.WorkSpace;
using VAdvantage.Model;
using VAdvantage.Dialogs;

namespace VAdvantage
{

    public interface IHost
    {
        void OnLoginCompleted();
        void OnMenuLoad();
        Explorer GetExplorer { get; }
        bool ShowBusyIndicator { get; set; }
        void StartMenuItemID(int id);
    }

    //  Number              description
    //  CR_01        Dont not show WelCome Screen on startUp


    public partial class MainPage : UserControl, IHost
    {
        #region Fields

        int _windowNum;
        StartPanel startPanel = null;
        private Ctx _ctx = null;
        private int _AD_User_ID;
        private int _AD_Role_ID;

        public static List<VTreeNode> favoriteNodeList = null;

        #endregion

        #region Constructor
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            //SetDateTimeOffSet();
           // Test.Visibility = Visibility.Visible;
        }

        private void SetDateTimeOffSet()
        {
            //var cl = AEnv.GetDataServiceClient();
            //cl.GetDateOffsetTicksCompleted += (s, e) =>
            //    {
            //        DataBase.GlobalVariable.DateTimeOffSet = e.Result;
            //    };
            //cl.GetDateOffsetTicksAsync();
            //cl.CloseAsync();
        }

        #endregion

        #region IHOST
        public void OnLoginCompleted()
        {
            UpdateLoginTime();

            BusyWindow.IsBusy = true;
            _AD_User_ID = _ctx.GetAD_User_ID();
            _AD_Role_ID = _ctx.GetAD_Role_ID();

            InitilizeStartMenu();
            Login.Begin();

            Explorer.Begin();
            desktop.IsEnabled = true;
            //desktop.Visibility = System.Windows.Visibility.Visible;
            
            /*** CR_01 ***/
            //bool showWelcomeScreen = false;

            //if (!DataBase.Ini.IsHideWelcomeScreen())
            //{
            //    showWelcomeScreen = true;
            //}
            //*** End ***/

            desktop.Effect = null;
            ThreadPool.QueueUserWorkItem(delegate
            {
                AEnv.IsUserEmployee();
                AEnv.IsWorkflowProcess();
                
                /***  CR_01 ***/
                //if (showWelcomeScreen)
                //{
                //    GetFormIDAndShowForm();
                //}

                Dispatcher.BeginInvoke(() => SetUI());
            });

            Desktop.MainScreen s = new Desktop.MainScreen();
            desktop.MainViewGrid = s;
            desktop.TopPanel = s.TopExpander;
            //desktop.RightPanel = s.RightExpander;

            s.LoadTopMenu(this);
        }

        /// <summary>
        /// Set Login time of client +Url
        /// </summary>
        private void UpdateLoginTime()
        {
            var client = AEnv.GetDataServiceBasicClient();
            client.UpdateLoginTimeCompleted += new EventHandler<DataServiceBasic.UpdateLoginTimeCompletedEventArgs>(client_UpdateLoginTimeCompleted);
            int AD_Client_ID = Envs.GetCtx().GetAD_Client_ID();
            client.UpdateLoginTimeAsync(AD_Client_ID, Envs.GetApplicationURL(), DataBase.GlobalVariable.TO_DATE(DateTime.Now, false));
            // client.UpdateLoginTimeAsync(1000000, "http://HarwinderGill.softwareonthecloud.com" , DataBase.GlobalVariable.TO_DATE(DateTime.Now, false));
            client.CloseAsync();

           

            
        }

        

        void client_UpdateLoginTimeCompleted(object sender, DataServiceBasic.UpdateLoginTimeCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                if (e.Result.Contains(","))
                {
                    //UpdateApplication update = new UpdateApplication();
                    //update.Show();
                    //update.Closed += (se, ev) =>
                    //    {
                    //        if ((bool)update.DialogResult)
                    //        {
                    //            return;
                    //        }
                    //    };
                }
            }
        }

        private void GetFormIDAndShowForm()
        {
            try
            {
                int id = Convert.ToInt32(DataBase.DB.ExecuteScalar("SELECT AD_Form_ID FROM AD_FORM WHERE Name = 'Welcome Screen'", null, null));
                if (id > 0)
                {
                    Dispatcher.BeginInvoke(delegate
                    {
                        FormFrame ff = new FormFrame();
                        ff.OpenForm(id);
                    });
                }
            }
            catch
            {

            }
        }


       

        public void OnMenuLoad()
        {
            LoginPage.Visibility = System.Windows.Visibility.Collapsed;

            favoriteNodeList = startPanel.GetFavoriteNode();
        }

        //public ProcessDialog GetProcessDialog
        //{
        //    get
        //    {
        //        return ProcessDialogProcess;
        //    }
        //}

        public Explorer GetExplorer
        {
            get { return desktop; }
        }

        public bool ShowBusyIndicator
        {
            get { return BusyWindow.IsBusy; }
            set { BusyWindow.IsBusy = value; }
        }

        #endregion

        private void InitilizeStartMenu()
        {
            int AD_Role_ID = _ctx.GetAD_Role_ID();
            int AD_Tree_ID;
            String ClientName = Envs.GetCtx().GetAD_Org_Name() + "_" + Envs.GetCtx().GetAD_User_Name();

            var client = Utility.AEnv.GetDataServiceClient();
            //var clientlog = Utility.AEnv.GetDataServiceBasic2Client();
            try
            {

                client.GetScalarCompleted += ((sender, e) =>
                    {

                        try
                        {
                            AD_Tree_ID = Util.GetValueOfInt(e.Result);
                        }
                        catch
                        {
                            AD_Tree_ID = 0;
                        }
                        if (AD_Tree_ID <= 0)
                        {
                            AD_Tree_ID = 10;	//Default Tree
                        }

                        //SecondStep
                        startPanel.InitMenu(AD_Tree_ID);

                        //BusyWindow.IsBusy = false;

                    });

                client.GetScalarAsync("SELECT COALESCE(r.AD_Tree_Menu_ID, ci.AD_Tree_Menu_ID)"
                        + "FROM AD_ClientInfo ci"
                        + " INNER JOIN AD_Role r ON (ci.AD_Client_ID=r.AD_Client_ID) "
                        + "WHERE AD_Role_ID=" + AD_Role_ID);
                client.CloseAsync();

                //clientlog.InitializeLogAsync(ClientName);
                //clientlog.CloseAsync();

            }
            catch
            {

            }

        }
        
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            _ctx = VAdvantage.Utility.Envs.GetContext();
            _windowNum = VAdvantage.Utility.Envs.CreateWindowNo(this);
            startPanel = new StartPanel(_windowNum, true, false, this);
            desktop.StartMeumItem = startPanel;
            LoginPage.LoginHost = this;

            VAdvantage.Utility.Envs.RegisterDesktop(desktop);
            VAdvantage.Utility.Envs.RegisterBusyIndicator(BusyWindow);

            LoginPage.InitLogin();

        }

        #region StartMenuItem

        public void StartMenuItemID(int id)
        {

        }

        #endregion

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //
            //InfoBPartner ip = new InfoBPartner(null, true, 2, "", true, false, "C_BPartner.IsActive='Y' AND C_BPartner.IsSummary='N'");
            ////InfoOrder ig = new InfoOrder(null, true, 3, "", false, "");
            //Info ig = new InfoGeneral(null, true, 2, "", "AD_User", "AD_User_ID", false, "");
            ////ig.Closed += new EventHandler(ip_Closed);
            //ig.Show();


        }

        void ip_Closed(object sender, EventArgs e)
        {
            //InfoGeneral ip = (sender as InfoGeneral);
            //Object obj = ip.GetSelectedKey();

            //textBox1.Text = obj.ToString();
        }

        private void Test_Click(object sender, RoutedEventArgs e)
        {
            //StatementOfAccounts act = new StatementOfAccounts();
            ///VAdvantage.Utility.Envs.RegisterWindowForm(act);
            //act.Show();
            //VAdvantage.ImpModule.Market m = new ImpModule.Market();
            //Envs.RegisterWindowForm(m);
            //m.Show();
            //Envs.ShowForm(m);
            //AccountWizard acct = new AccountWizard();
            //Envs.RegisterWindowForm(acct);
            //acct.Show();

        }

        private void DesktopShortcut_DoubleClick(object sender, RoutedEventArgs e)
        {
            DesktopShortcut shortCut = (DesktopShortcut)sender;

            if (shortCut.ActionName.Equals("Preference"))
            {
                VAdvantage.Framework.UserPreference pf = new UserPreference();
                pf.Explorer = desktop;
                pf.Show();
            }
            else if (shortCut.ActionName.Equals("RoleCenter"))
            {
                //FramePane dash = new FramePane();
                //FramePaneView dash = new FramePaneView();
                // RoleCenter dash = new RoleCenter();
                //DashBoard dash = new DashBoard();
                // Utility.Envs.RegisterWindowForm(dash);
                // dash.Show();
            }

            else if (shortCut.ActionName.Equals("DashBoard"))
            {
                DashBoard dash = new DashBoard();
                Utility.Envs.RegisterWindowForm(dash);
                dash.Show();
            }
            //else if (shortCut.ActionName.Equals("InfoForm"))
            //{
            //    AEnv.GetInfoPopup();



            //    //InfoForms
            //}

            else if (shortCut.ActionName.Equals("Calender"))
            {
                //Scheduler.VSchedulerForm frm = new Scheduler.VSchedulerForm();

                //Utility.Envs.RegisterWindowForm(frm);
                //frm.Show();

            }


            else if (shortCut.ActionName.Equals("EMail"))
            {



                // Save InitParams
                //if (e.InitParams != null)
                //{
                //    foreach (var item in e.InitParams)
                //    {
                //        this.Resources.Add(item.Key, item.Value);
                //    }
                //}

                // Create & show startup view
                //var mailForm = new MailForm();
                // mainView.DataContext = mainViewModel;
                //Utility.Envs.RegisterWindowForm(mailForm);
                //mailForm.Show();
                //Utility.Envs.RegisterWindowForm(dash);

            }
            //Other ShortCuts
        }

        //Other UI
        private void SetUI()
        {
            //if (AEnv.IsUserEmployee())
            {
                //desktop.DesktopShortCutsBottom[0].Visibility = System.Windows.Visibility.Visible;
            }
        }
    }
}
